﻿using HandyControl.Data;
using HandyControl.Tools;
using LpbPrj.Client.Controls;
using LpbPrj.Client.Data;
using LpbPrj.Client.Module;
using LpbPrj.Client.Tools.Helper;
using LpbPrj.Client.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Regions;
using Prism.Unity;
using System;
using System.Diagnostics;
using System.Reflection;
using System.Security.Principal;
using System.Windows;
using Unity;
using Unity.Microsoft.DependencyInjection;

namespace LpbPrj.Client
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            var versionInfo = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location);

            bool exist = false;
            {
                var current = Process.GetCurrentProcess();
                foreach (var process in Process.GetProcessesByName(current.ProcessName))
                {
                    if (process.Id != current.Id)
                    {
                        Win32Helper.SetForegroundWindow(process.MainWindowHandle);
                        current.Kill();
                        exist = true;
                        break;
                    }
                }
            }

            if (!exist)
            {
                this.DispatcherUnhandledException += App_DispatcherUnhandledException;

                GlobalData.Init();
                ConfigHelper.Instance.SetLang(GlobalData.Config.Lang);

                string cover = "/Resources/Img/Cover.jpg" ;
                var splashScreen = new SplashScreen(cover);
                splashScreen.Show(true);
                ShutdownMode = ShutdownMode.OnMainWindowClose;

                if (GlobalData.Config.Skin != SkinType.Default)
                {
                    UpdateSkin(GlobalData.Config.Skin);
                }

                base.OnStartup(e);
            }
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            HandyControl.Controls.MessageBox.Show(e.Exception.Message, GlobalData.Config.SoftTitle, MessageBoxButton.OK);
            //处理完后，我们需要将Handler=true表示已此异常已处理过
            e.Handled = true;
        }

        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            //初始加载页
            var regionManager = Container.Resolve<IRegionManager>();
            regionManager.RegisterViewWithRegion("LoadingRegion", typeof(WaitingView));
        }

        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            moduleCatalog.AddModule<AScanTestModule>(); 
            return;
        }

        protected override IContainerExtension CreateContainerExtension()
        {
            ///https://www.andicode.com/prism/wpf/logging/2021/05/21/Logging-In-Prism.html

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddLogging(loggingBuilder =>
            {
                loggingBuilder.ClearProviders();
                loggingBuilder.SetMinimumLevel(LogLevel.Trace);
                loggingBuilder.AddLog4Net("CfgFiles/log4net.config");
            });

            var container = new UnityContainer();
            container.BuildServiceProvider(serviceCollection);

            return new UnityContainerExtension(container);
        }

        /// <summary>
        /// 为当前正在运行的程序创建一个快捷方式。
        /// </summary>
        /// <param name="lnkFilePath">快捷方式的完全限定路径。</param>
        /// <param name="args">快捷方式启动程序时需要使用的参数。</param>
        private void CreateShortcut(string lnkFilePath, string args = "")
        {
            var shellType = Type.GetTypeFromProgID("WScript.Shell");
            dynamic shell = Activator.CreateInstance(shellType);
            var shortcut = shell.CreateShortcut(lnkFilePath);
            shortcut.TargetPath = Assembly.GetEntryAssembly().Location;
            shortcut.Arguments = args;
            shortcut.WorkingDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            shortcut.Save();
        }

        /// <summary>
        /// 判断当前程序是不是管理员权限运行
        /// </summary>
        /// <returns></returns>
        private bool IsAdministrator()
        {
            WindowsIdentity current = WindowsIdentity.GetCurrent();
            WindowsPrincipal windowsPrincipal = new WindowsPrincipal(current);
            //WindowsBuiltInRole可以枚举出很多权限，例如系统用户、User、Guest等等
            return windowsPrincipal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        /// <summary>
        /// 修改样式
        /// </summary>
        /// <param name="skin"></param>
        public void UpdateSkin(SkinType skin)
        {
            var skins0 = Resources.MergedDictionaries[0];
            skins0.MergedDictionaries.Clear();
            skins0.MergedDictionaries.Add(ResourceHelper.GetSkin(skin));
            skins0.MergedDictionaries.Add(ResourceHelper.GetSkin(typeof(App).Assembly, "Resources/Themes", skin));

            var skins1 = Resources.MergedDictionaries[1];
            skins1.MergedDictionaries.Clear();
            skins1.MergedDictionaries.Add(new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/HandyControl;component/Themes/Theme.xaml")
            });
            skins1.MergedDictionaries.Add(new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/" + typeof(App).Assembly.GetName().Name + ";component/Resources/Themes/Theme.xaml")
            });
            Current.MainWindow?.OnApplyTemplate();
        }


    }

}
